import React, { Fragment, RefObject, useEffect, useState, useMemo, useRef, FC } from 'react'
import { request, useRequest, setPageNavBar, useLocation, useNavigate, Link, useParams, useSearchParams } from 'alita'
import { Radio, DotLoading, SearchBar, Stepper, NoticeBar, Grid, Image, Avatar, NavBar, Picker, List, ProgressCircle, Tag, Popup, CheckList, Result, Form, Input, Button, Dialog, Checkbox, TextArea, DatePicker, CascadePicker, Selector, Slider, Switch, Cascader, Space, SideBar, Divider, AutoCenter, CapsuleTabs } from 'antd-mobile'
import { SearchOutline, MoreOutline, CloseOutline } from 'antd-mobile-icons'
import type { DatePickerRef } from 'antd-mobile/es/components/date-picker'
import type { PickerActions } from 'antd-mobile/es/components/picker'
import { Content, Page } from '@alita/flow';
import { ACCESSTOKEN, checkAuthorize } from '@/utils/authorize';

import type { Block, DetailResult, WorkFlow, Opportunity, WeiXinUser } from '@/pages/types/type'
import { DemoBlock } from '@/components/demos-util'

import dayjs from 'dayjs'
import { OtherCountInPartake } from '@/components/partake';

import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { EditSOutline } from 'antd-mobile-icons'
import { WeiXinUserPicker } from '@/pages/selectors/wei-xin-user';
import { PickerValue, PickerValueExtend, PickerColumnItem, PickerColumn } from 'antd-mobile/es/components/picker-view';
import type { CascaderProps, CascaderValueExtend, CascaderOption, CascaderRef } from 'antd-mobile/es/components/cascader';
import { DATE_FOMRAT, DATE_TIME_FORMAT } from '@/constants'
import { PickerDate } from 'antd-mobile/es/components/date-picker/util'

export const UpdateNumberPopup = ({ title, url, current, origin, onSuccess }: { title: string, url: string, current?: number, origin: number, onSuccess: () => void }) => {
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [visible, setVisible] = useState<boolean>(false);
    type FieldType = { value: string, remark: string }
    async function onFinish(values: FieldType) {
        setIng(true);
        setFail(undefined);
        setSuccess(undefined);
        let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ ...values, origin }))
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then(async (x: DetailResult<number>) => {
                    console.log(x);
                    const { data, code, msg } = x;
                    console.log('history id =', data);
                    if (code === 0) {
                        onSuccess();
                        setSuccess(msg);
                        setVisible(false);
                    } else {
                        setFail(msg);
                    }
                }).catch(reason => {
                    setFail(reason);
                })
            }
        }).catch((reason: any) => {
            console.error(reason);
            setFail(`发生错误：${reason}`)
        }).finally(() => {
            setIng(false);
        })
    }

    return <React.Fragment>
        <EditSOutline onClick={() => setVisible(true)} />
        <Popup
            visible={visible}
            onMaskClick={() => { setVisible(false) }}
            destroyOnClose
        >
            <DemoBlock padding={8} title={`修改${title}`}>
                <Form
                    layout={'vertical'}
                    onFinish={onFinish}
                    footer={<>
                        {fail !== undefined && <NoticeBar
                            extra={
                                <Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>
                            }
                            content={fail}
                            color='alert'
                        />}
                        <Button block type='submit'
                            disabled={ing || fail !== undefined || success !== undefined}
                            loading={ing}
                            color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                >
                    <Form.Item
                        initialValue={current}
                        rules={[{ required: true, max: 999999999, min: 0, type: 'number' }]}
                        name='value'
                        label={title}
                    >
                        <Stepper style={{ width: '80%' }} step={10000} max={999999999} min={0} digits={2} />
                    </Form.Item>
                    <Form.Item name='remark' label={'备注'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                        <TextArea placeholder='备注' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                    </Form.Item>
                </Form>
            </DemoBlock>
        </Popup>
    </React.Fragment>
}

export const UpdateNamePopup = ({ title, url, current, origin, onSuccess }: { title: string, url: string, current?: string, origin: number, onSuccess: () => void }) => {
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [visible, setVisible] = useState<boolean>(false);
    const [restricts, setRestricts] = useState<string[]>([]);
    const [loadingTimes, setLoadingTimes] = useState<number>(0);
    const [loadFails, setLoadFails] = useState<string[]>([]);
    const [loadOK, setLoadOK] = useState<string | undefined>(undefined);

    type FieldType = { value: string, remark: string }

    useEffect(() => {
        if(visible){
            let time = 1;
            let response: Promise<Response> = fetch(`${urlPrefix}${url}/get-restricts`, getRequestInit())
            response.then((rsp: Response) => {
                console.log(rsp);
                if (rsp.ok) {
                    rsp.json().then(async ({ data, code, msg }: DetailResult<string[]>) => {
                        if (code === 0) {
                            setRestricts(data!);
                            setLoadOK(msg);
                        } else { setLoadFails([...loadFails, msg]); }
                    }).catch(reason => { setLoadFails([...loadFails, reason]); })
                }
            }).catch((reason: any) => {
                console.error(reason);
                setLoadFails([...loadFails, `发生错误：${reason}`])
            }).finally(() => {
                setLoadingTimes(--time)
            })
        }
    }, [url,visible])

    async function onFinish(values: FieldType) {
        setIng(true);
        setFail(undefined);
        setSuccess(undefined);
        let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ ...values, origin }))
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then((x: DetailResult<number>) => {
                    console.log(x);
                    const { data, code, msg } = x;
                    console.log('history id=', data);
                    if (code === 0) {
                        setSuccess(msg);
                        onSuccess();
                        setVisible(false);
                    } else { setFail(msg); }
                }).catch(reason => { setFail(reason); })
            }
        }).catch((reason: any) => {
            console.error(reason); setFail(`发生错误：${reason}`)
        }).finally(() => { setIng(false); })
    }
    const r = /@jakarta.validation.constraints.Size\(min=(\d+), max=(\d+)\)/i

    let mmIndex = restricts.findIndex(g => r.test(g));
    let smatch = mmIndex >= 0 ? restricts[mmIndex].match(r) : undefined;

    return <React.Fragment>
        <EditSOutline onClick={() => setVisible(true)} />
        <Popup
            visible={visible}
            onMaskClick={() => { setVisible(false) }}
            destroyOnClose
        >
            <DemoBlock padding={8} title={`修改${title}${loadingTimes > 0 ? 'loading...' : ''}`}>
                <Form
                    layout={'vertical'}
                    onFinish={onFinish}
                    footer={<>
                        {fail !== undefined && <NoticeBar
                            extra={<Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>}
                            content={fail}
                            color='alert'
                        />}

                        <Button block type='submit'
                            disabled={loadingTimes > 0 || ing || fail !== undefined || success !== undefined}
                            loading={ing}
                            color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                >
                    <Form.Item name='value' label={title} initialValue={current} rules={[{ required: true, message: title }]}>
                        <TextArea placeholder={title} showCount maxLength={smatch ? parseInt(smatch[2]) : 200} />
                    </Form.Item>
                    <Form.Item name='remark' label={'为什么要修改'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                        <TextArea placeholder='为什么要修改' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                    </Form.Item>
                </Form>
            </DemoBlock>
        </Popup>
    </React.Fragment>
}

export const UpdateWeiXinUser: FC<{ title: string, current?: WeiXinUser, url: string, origin: string | number, onSuccess: () => void }> = ({ title, url, origin, current, onSuccess }) => {
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [visible, setVisible] = useState<boolean>(false);
    type FieldType = { value: string, remark: string }
    async function onFinish(values: FieldType) {
        setIng(true);
        setFail(undefined);
        setSuccess(undefined);
        let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ ...values, origin }))
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then((x: DetailResult<number>) => {
                    console.log(x);
                    const { data, code, msg } = x;
                    console.log('update history id=', data);
                    if (code === 0) {
                        setSuccess(msg);
                        onSuccess();
                    } else { setFail(msg); }
                }).catch(reason => { setFail(reason); })
            }
        }).catch((reason: any) => {
            console.error(reason); setFail(`发生错误：${reason}`)
        }).finally(() => { setIng(false); })
    }

    return <React.Fragment>
        <EditSOutline onClick={() => setVisible(true)} />
        <Popup visible={visible}   onMaskClick={() => { setVisible(false) }}  destroyOnClose>
            <DemoBlock padding={8} title={`修改${title}`}>
                <Form
                    layout={'vertical'}
                    onFinish={onFinish}
                    footer={<>
                        {fail !== undefined && <NoticeBar
                            extra={<Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>}
                            content={fail} color='alert'
                        />}
                        <Button block type='submit'
                            disabled={ing || fail !== undefined || success !== undefined} loading={ing}
                            color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                >
                    <WeiXinUserPicker name='value' label={`新${title}`}  required  />
                    <Form.Item name='remark' label={'为什么要修改'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                        <TextArea placeholder='为什么要修改' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                    </Form.Item>
                </Form>
            </DemoBlock>
        </Popup>
    </React.Fragment>
}

export const PickerUpdatePopup:
    FC<{ title: string, url: string, current?: any, origin: number | string, onSuccess: () => void, itemsFromUrl: string }>
    = ({ title, url, current, origin, onSuccess, itemsFromUrl }) => {
        const [ing, setIng] = useState<boolean>(false);
        const [success, setSuccess] = useState<string>();
        const [fail, setFail] = useState<string>();
        const [visible, setVisible] = useState<boolean>(false);
        const [columns, setColumns] = useState<PickerColumn[]>([]);
        const [loadingTimes, setLoadingTimes] = useState<number>(1);
        const [loadFails, setLoadFails] = useState<string[]>([]);
        const [loadOK, setLoadOK] = useState<string | undefined>(undefined);

        type FieldType = { value: PickerColumnItem[], remark: string }

        useEffect(() => {
            // 每一个，上面 loadingTime已经设置为1了，所以不用再设置
            //setLoadingTimes(loadingTimes+1);
            let response: Promise<Response> = fetch(`${urlPrefix}${itemsFromUrl}`, getRequestInit())
            response.then((rsp: Response) => {
                console.log(rsp);
                if (rsp.ok) {
                    rsp.json().then(async ({ data, code, msg }: DetailResult<PickerColumnItem[]>) => {
                        if (code === 0) {
                            setColumns([data!,]);
                            console.log(data!)
                            setLoadOK(msg);
                            setVisible(false);
                        } else { setLoadFails([...loadFails, msg]); }
                    }).catch(reason => { setLoadFails([...loadFails, reason]); })
                }
            }).catch((reason: any) => {
                console.error(reason);
                setLoadFails([...loadFails, `发生错误：${reason}`])
            }).finally(() => {
                setLoadingTimes(loadingTimes - 1)
            })
        }, [url])

        async function onFinish(values: FieldType) {
            setIng(true);
            setFail(undefined);
            setSuccess(undefined);
            let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ ...values, origin }))
            response.then((rsp: Response) => {
                console.log(rsp);
                if (rsp.ok) {
                    rsp.json().then((x: DetailResult<number>) => {
                        console.log(x);
                        const { data, code, msg } = x;
                        console.log('history id=', data);
                        if (code === 0) {
                            setSuccess(msg);
                            onSuccess();
                        } else { setFail(msg); }
                    }).catch(reason => { setFail(reason); })
                }
            }).catch((reason: any) => {
                console.error(reason); setFail(`发生错误：${reason}`)
            }).finally(() => { setIng(false); })
        }

        return <React.Fragment>
            <EditSOutline onClick={() => setVisible(true)} />
            <Popup
                visible={visible}
                onMaskClick={() => { setVisible(false) }}
                destroyOnClose
            >
                <DemoBlock padding={8} title={`修改${title}${loadingTimes > 0 ? 'loading...' : ''}`}>
                    <Form
                        layout={'vertical'}
                        onFinish={onFinish}
                        footer={<>
                            {fail !== undefined && <NoticeBar
                                extra={<Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>}
                                content={fail}
                                color='alert'
                            />}

                            <Button block type='submit'
                                disabled={loadingTimes > 0 || ing || fail !== undefined || success !== undefined}
                                loading={ing}
                                color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                    >

                        {columns.length > 0 && <Form.Item name='value' label={title} rules={[{ required: true, message: title }]}
                            trigger='onConfirm'
                            onClick={(e, pickRef: RefObject<PickerActions>) => {
                                pickRef.current?.open()
                            }}
                        >
                            <Picker columns={columns}>
                                {value => value.map(v => v?.label).join('/')}
                            </Picker>
                        </Form.Item>}
                        <Form.Item name='remark' label={'为什么要修改'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                            <TextArea placeholder='为什么要修改' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                        </Form.Item>
                    </Form>
                </DemoBlock>
            </Popup>
        </React.Fragment>
    }



export const CascadePickerUpdatePopup:
    FC<{ title: string, url: string, current?: any, origin: number | string, onSuccess: () => void, itemsFromUrl: string }>
    = ({ title, url, current, origin, onSuccess, itemsFromUrl }) => {
        const [ing, setIng] = useState<boolean>(false);
        const [success, setSuccess] = useState<string>();
        const [fail, setFail] = useState<string>();
        const [visible, setVisible] = useState<boolean>(false);
        const [options, setOptions] = useState<CascaderOption[]>([]);
        const [loadingTimes, setLoadingTimes] = useState<number>(1);
        const [loadFails, setLoadFails] = useState<string[]>([]);
        const [loadOK, setLoadOK] = useState<string | undefined>(undefined);

        type FieldType = { value: CascaderOption[], remark: string }

        useEffect(() => {
            // 每一个，上面 loadingTime已经设置为1了，所以不用再设置
            //setLoadingTimes(loadingTimes+1);
            let response: Promise<Response> = fetch(`${urlPrefix}/${itemsFromUrl}`, getRequestInit())
            response.then((rsp: Response) => {
                console.log(rsp);
                if (rsp.ok) {
                    rsp.json().then(async ({ data, code, msg }: DetailResult<CascaderOption[]>) => {
                        if (code === 0) {
                            setOptions(data!);
                            console.log(data!)

                            setLoadOK(msg);
                        } else { setLoadFails([...loadFails, msg]); }
                    }).catch(reason => { setLoadFails([...loadFails, reason]); })
                }
            }).catch((reason: any) => {
                console.error(reason);
                setLoadFails([...loadFails, `发生错误：${reason}`])
            }).finally(() => {
                setLoadingTimes(loadingTimes - 1)
            })
        }, [url])

        async function onFinish(values: FieldType) {
            setIng(true);
            setFail(undefined);
            setSuccess(undefined);
            let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ ...values, origin }))
            response.then((rsp: Response) => {
                console.log(rsp);
                if (rsp.ok) {
                    rsp.json().then((x: DetailResult<number>) => {
                        console.log(x);
                        const { data, code, msg } = x;
                        console.log('history id=', data);
                        if (code === 0) {
                            setSuccess(msg);
                            onSuccess();
                            setVisible(false);
                        } else { setFail(msg); }
                    }).catch(reason => { setFail(reason); })
                }
            }).catch((reason: any) => {
                console.error(reason); setFail(`发生错误：${reason}`)
            }).finally(() => { setIng(false); })
        }

        return <React.Fragment>
            <EditSOutline onClick={(e:any) =>{ 
                setVisible(true);
                e.stopPropagation();
            }} />
            <Popup
                visible={visible}
                onMaskClick={() => { setVisible(false) }}
                destroyOnClose
            >
                <DemoBlock padding={8} title={`修改${title}${loadingTimes > 0 ? 'loading...' : ''}`}>
                    <Form
                        layout={'vertical'}
                        onFinish={onFinish}
                        footer={<>
                            {fail !== undefined && <NoticeBar
                                extra={<Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>}
                                content={fail}
                                color='alert'
                            />}
                            <Button block type='submit'
                                disabled={loadingTimes > 0 || ing || fail !== undefined || success !== undefined}
                                loading={ing}
                                color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                    >
                        <Form.Item name="value" label={title}
                            onClick={(e: any, ref: RefObject<CascaderRef>) => { console.log(e); console.log(ref); ref.current?.open(); }}
                            rules={[{ required: true, message: title }]} trigger="onConfirm" validateTrigger="onConfirm"
                        ><Cascader options={options}>
                                {(items) => { return items.every((item) => item === null) ? '未选择' : items.map((item) => item?.label ?? "未选择").join("-"); }}</Cascader>
                        </Form.Item>
                        <Form.Item name='remark' label={'为什么要修改'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                            <TextArea placeholder='为什么要修改' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                        </Form.Item>
                    </Form>
                </DemoBlock>
            </Popup>
        </React.Fragment>
    }

export const UpdateDatePopup = ({ title, url, current, origin, onSuccess }: { title: string, url: string, current?: string, origin: number, onSuccess: () => void }) => {
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [visible, setVisible] = useState<boolean>(false);
    type FieldType = { value: PickerDate, remark: string }

    async function onFinish(values: FieldType) {
        setIng(true);
        setFail(undefined);
        setSuccess(undefined);
        const { value,remark} = values;
        let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ value:dayjs(value).format(DATE_FOMRAT), origin,remark }))
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then(async (x: DetailResult<number>) => {
                    console.log(x);
                    const { data, code, msg } = x;
                    console.log('history id =', data);
                    if (code === 0) {
                        onSuccess();
                        setSuccess(msg);
                        setVisible(false);
                    } else {
                        setFail(msg);
                    }
                }).catch(reason => {
                    setFail(reason);
                })
            }
        }).catch((reason: any) => {
            console.error(reason);
            setFail(`发生错误：${reason}`)
        }).finally(() => {
            setIng(false);
        })
    }

    return <React.Fragment>
        <EditSOutline onClick={() => setVisible(true)} />
        <Popup
            visible={visible}
            onMaskClick={() => { setVisible(false) }}
            destroyOnClose
        >
            <DemoBlock padding={8} title={`修改${title}`}>
                <Form
                    layout={'vertical'}
                    onFinish={onFinish}
                    footer={<>
                        {fail !== undefined && <NoticeBar
                            extra={
                                <Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>
                            }
                            content={fail}
                            color='alert'
                        />}
                        <Button block type='submit'
                            disabled={ing || fail !== undefined || success !== undefined}
                            loading={ing}
                            color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                >
                    <Form.Item
                        name='value'
                        label={title}
                        trigger='onConfirm'
                        rules={[{ required: false, message: title }]}
                        onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                            datePickerRef.current?.open()
                        }}>
                        <DatePicker precision={'day'} max={new Date()}  >
                            {value => value ? dayjs(value).format(DATE_FOMRAT) : '请选择日期'}
                        </DatePicker>
                    </Form.Item>
                    <Form.Item name='remark' label={'备注'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                        <TextArea placeholder='备注' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                    </Form.Item>
                </Form>
            </DemoBlock>
        </Popup>
    </React.Fragment>
}


export const UpdatTimePopup = ({ title, url, current, origin, onSuccess }: { title: string, url: string, current?: string, origin: number, onSuccess: () => void }) => {
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [visible, setVisible] = useState<boolean>(false);
    type FieldType = { value: PickerDate, remark: string }
    
    async function onFinish(values: FieldType) {
        setIng(true);
        setFail(undefined);
        setSuccess(undefined);
        
        let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({  origin,...values }))
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then(async (x: DetailResult<number>) => {
                    console.log(x);
                    const { data, code, msg } = x;
                    console.log('history id =', data);
                    if (code === 0) {
                        onSuccess();
                        setSuccess(msg);
                        setVisible(false);
                    } else {
                        setFail(msg);
                    }
                }).catch(reason => {
                    setFail(reason);
                })
            }
        }).catch((reason: any) => {
            console.error(reason);
            setFail(`发生错误：${reason}`)
        }).finally(() => {
            setIng(false);
        })
    }

    return <React.Fragment>
        <EditSOutline onClick={() => setVisible(true)} />
        <Popup
            visible={visible}
            onMaskClick={() => { setVisible(false) }}
            destroyOnClose
        >
            <DemoBlock padding={8} title={`修改${title}`}>
                <Form
                    layout={'vertical'}
                    onFinish={onFinish}
                    footer={<>
                        {fail !== undefined && <NoticeBar
                            extra={
                                <Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>
                            }
                            content={fail}
                            color='alert'
                        />}
                        <Button block type='submit'
                            disabled={ing || fail !== undefined || success !== undefined}
                            loading={ing}
                            color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                >
                    <Form.Item
                        name='value'
                        label={title}
                        trigger='onConfirm'
                        rules={[{ required: false, message: title }]}
                        onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                            datePickerRef.current?.open()
                        }}>
                        <DatePicker precision={'hour'} max={new Date()}  >
                            {value => value ? dayjs(value).format(DATE_TIME_FORMAT) : '请选择时间'}
                        </DatePicker>
                    </Form.Item>
                    <Form.Item name='remark' label={'备注'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                        <TextArea placeholder='备注' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                    </Form.Item>
                </Form>
            </DemoBlock>
        </Popup>
    </React.Fragment>
}

export const UpdateFieldPopup: FC<{ title: string, current?: any, url: string, origin: string | number, onSuccess: () => void ,selector:React.ReactElement }> = ({ title, url, origin, selector, onSuccess }) => {
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [visible, setVisible] = useState<boolean>(false);
    type FieldType = { value: string, remark: string }
    async function onFinish(values: FieldType) {
        setIng(true);
        setFail(undefined);
        setSuccess(undefined);
        let response: Promise<Response> = fetch(`${urlPrefix}${url}/update`, postRequestInit({ ...values, origin }))
        response.then((rsp: Response) => {
            console.log(rsp);
            if (rsp.ok) {
                rsp.json().then((x: DetailResult<number>) => {
                    console.log(x);
                    const { data, code, msg } = x;
                    console.log('update history id=', data);
                    if (code === 0) {
                        setSuccess(msg);
                        onSuccess();
                    } else { setFail(msg); }
                }).catch(reason => { setFail(reason); })
            }
        }).catch((reason: any) => {
            console.error(reason); setFail(`发生错误：${reason}`)
        }).finally(() => { setIng(false); })
    }

    return <React.Fragment>
        <EditSOutline onClick={() => setVisible(true)} />
        <Popup visible={visible}   onMaskClick={() => { setVisible(false) }}  destroyOnClose>
            <DemoBlock padding={8} title={`修改${title}`}>
                <Form
                    layout={'vertical'}
                    onFinish={onFinish}
                    footer={<>
                        {fail !== undefined && <NoticeBar
                            extra={<Space style={{ '--gap': '12px' }}> <span onClick={() => setFail(undefined)} >再试一次</span> </Space>}
                            content={fail} color='alert'
                        />}
                        <Button block type='submit'
                            disabled={ing || fail !== undefined || success !== undefined} loading={ing}
                            color='primary' size='large'>{success !== undefined ? '已修改' : (fail !== undefined ? '执行失败' : '修改')}</Button></>}
                >
                    {selector}
                    <Form.Item name='remark' label={'为什么要修改'} initialValue={'无'} rules={[{ required: true, message: '备注' }]}>
                        <TextArea placeholder='为什么要修改' autoSize={{ minRows: 2, maxRows: 3 }} showCount maxLength={200} />
                    </Form.Item>
                </Form>
            </DemoBlock>
        </Popup>
    </React.Fragment>
}

export const FieldLastUpdate:FC<{ origin:number|string, url:string }> =({ origin, url })=>{

    
}